package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.dto.ArticleDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Override
    public ResponseResult<Long> saveApArticle(ArticleDto dto) {
//        需要做一个判断  判断是新增还是修改  取决于dto中是否有id

        if (dto.getId()==null) { //新增  先保存主表 ap_article  再保存从表ap_article_content
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            apArticle.setCreatedTime(new Date());
            this.save(apArticle);

            ApArticleContent apArticleContent = new ApArticleContent();
//            apArticleContent.setId(); //雪花算法 不用我们处理
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);


            return ResponseResult.okResult(apArticle.getId());

        }else{  // 修改
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            this.updateById(apArticle);

//            update ap_article_content set content=?? where article_id=??
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent,dto.getContent()); //set content=??

            updateWrapper.eq(ApArticleContent::getArticleId,apArticle.getId()); //where article_id=??

            apArticleContentService.update(updateWrapper);
            return ResponseResult.okResult(apArticle.getId());
        }



    }
}
